<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="../inc/js.jsp"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>数据查询</title>
    <jsp:include page="../inc/css.jsp"/>
    <style type="text/css">
        .searchDiv {
            margin-top: 10px;
            margin-left: 10px;
        }
    </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <jsp:include page="../inc/menu.jsp"/>

    <div class="content-wrapper">
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card" style="margin-top: 10px">
                        <div class="card-header">
                            <div class="form-inline">
                                <div class="form-group searchDiv">
                                    <input id="searchDate" readonly placeholder="查询日期" class="form-control" style="width: 150px;"/>
                                </div>

                                <div class="form-group searchDiv">
                                    <select id="companyList" class="form-control" onchange="_dataList.fn.getDeviceList()">
                                        <option value="">全部公司</option>
                                    </select>
                                </div>

                                <div class="form-group searchDiv">
                                    <select id="deviceList" class="form-control">
                                        <option value="">全部设备</option>
                                    </select>
                                </div>

                                <div class="form-group searchDiv">
                                    <select id="typeList" class="form-control">
                                        <option value="2011">实时数据</option>
                                        <option value="2051">分钟数据</option>
                                        <option value="2061">小时数据</option>
                                        <option value="2031">日均数据</option>
                                    </select>
                                </div>

                                <button type="button" title="查询" class="btn btn-success searchDiv" onclick="_dataList.fn.reloadData()">查询</button>
                                <%--                                <button type="button" title="导出" class="btn btn-info searchDiv" style="margin-left: 10px;" onclick="_dataList.fn.exportData()">导出</button>--%>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <!--以下为两个必须div元素-->
                                <table class="table table-striped table-bordered table-hover" id="dataTables" style="width: 99%">
                                    <colgroup id="tableBackColor"></colgroup>
                                    <thead>
                                    <tr id="tableBaseTr"></tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<script type="text/javascript">
    let _dataList = {
        v: {
            list: [],
            tableArrangeList: [],
            dTable: null,
            masterCompanyId: 0
        },
        fn: {
            init: function () {
                laydate.render({
                    elem: '#searchDate'
                    , type: 'date'
                    , btns: ['now', 'confirm']
                    , value: $tutu.getRecentDay(0)
                });

                let masterCompanyId = $('#masterCompanyId').val();

                if (Number(masterCompanyId) > 0) {
                    _dataList.v.masterCompanyId = Number(masterCompanyId);

                    $('#companyList').css('display', 'none');
                    _dataList.fn.getDeviceList();
                } else {
                    _dataList.fn.getCompanyList();
                }
            },
            getNowWeekDate: function () {
                let date = new Date();
                let split = "-";
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                return year + split + month + split + strDate;
            },
            getLastWeekDate: function () {
                let time = (new Date).getTime() - 7 * 24 * 60 * 60 * 1000;
                let resultTime = new Date(time);
                return resultTime.getFullYear() + "-" + (resultTime.getMonth() > 9 ? (resultTime.getMonth() + 1) : "0" + (resultTime.getMonth() + 1)) + "-" + (resultTime.getDate() > 9 ? (resultTime.getDate()) : "0" + (resultTime.getDate()));
            },
            getCompanyList: function () {
                $.post('common/companyList', {
                    id: 1
                }, function (result) {
                    if (result.length > 0) {
                        let content = '';
                        $.each(result, function (i, item) {
                            content += '<option value="' + item.id + '">' + item.name + '</option>';
                        });

                        $('#companyList').append(content);
                    } else {
                        info("暂无公司数据", "error");
                    }
                });
            },
            getDeviceList: function () {
                let companyId;

                if (_dataList.v.masterCompanyId > 0) {
                    companyId = _dataList.v.masterCompanyId;
                } else {
                    companyId = $('#companyList').val();
                }

                if (null != companyId && companyId !== '') {
                    $.post('common/deviceList', {
                        companyId: companyId
                    }, function (result) {
                        if (result.length > 0) {
                            let content = '<option value="">全部设备</option>';

                            $.each(result, function (i, item) {
                                content += '<option value="' + item.code + '">' + item.name + '</option>';
                            });

                            $('#deviceList').html(content);
                        }
                    });
                } else {
                    $('#deviceList').html('<option value="">全部设备</option>');
                }
            },
            exportData: function () {
                let searchDate = $('#searchDate').val();
                let deviceCode = $('#deviceList').val();

                if (null == deviceCode || deviceCode === '') {
                    info('请先选择设备', 'warning');
                    return;
                }

                let url = 'backend/excel/exportDeviceData?deviceCode=' + deviceCode + '&type=' + $('#typeList').val() + '&keyWord=' + $('#searchKeyWord').val();

                if (searchDate.trim().length > 0) {
                    url += '&searchDate=' + searchDate;
                }

                window.location.href = url;
            },
            blindTableTitle: function (result) {
                let backColor = '';
                let trHtml = '';

                if (result.length > 0) {
                    $.each(result, function (i, item) {
                        if (i % 2 === 0) {
                            backColor += '<col class="gradeA odd"/>';
                        } else {
                            backColor += '<col class="gradeA even"/>';
                        }

                        $('#tableBackColor').html(backColor);

                        trHtml += '<th>' + item.name + '</th>';

                        let itemName = item.name;

                        if (item.unit !== '') itemName = item.name + '（' + item.unit + '）';

                        _dataList.v.tableArrangeList.push({
                            title: itemName,
                            data: item.code
                        });
                    });
                }

                $('#tableBaseTr').html(trHtml);
                $('#tableBackColor').next().next().html('');
            },
            loadTableTitle: function () {
                return new Promise(function (resolve, reject) {
                    // 先查询对应的列数
                    $.post('common/codeDictList', {
                        deviceCode: $("#deviceList").val(),
                        type: $("#typeList").val()
                    }, function (result) {
                        resolve(result);
                    });
                });
            },
            reloadData: function () {
                let searchDate = $('#searchDate').val();
                let deviceId = $('#deviceList').val();

                if (null == searchDate || searchDate === '') {
                    info('请先选择查询日期', 'warning');
                    return;
                }

                if (null == deviceId || deviceId === '') {
                    info('请先选择设备', 'warning');
                    return;
                }

                _dataList.v.tableArrangeList = [];

                _dataList.fn.destroyDataTable();
                _dataList.fn.loadTableTitle().then(function (data) {
                    _dataList.fn.blindTableTitle(data);

                    _dataList.v.list = [];

                    if (data.length > 0) {
                        _dataList.fn.dataTableInit();
                    } else {
                        console.error('No valid data or columns available for DataTable initialization.');
                    }

                }).catch(function (error) {
                    console.error('Error fetching data 1:', error);
                });
            },
            dataTableInit: function () {
                _dataList.v.dTable = $tutu.dataTable($('#dataTables'), {
                    "processing": true,
                    "serverSide": true,
                    "autoWidth": true,//自动计算宽度
                    "lengthChange": false,//是否允许用户改变表格每页显示的记录数
                    "searching": false,
                    "ordering": false,
                    'destroy': true,
                    "ajax": {
                        "url": "backend/data/list",
                        "type": "POST",
                        "dataSrc": function (json) {
                            // 获取表头所有列名（从columns配置中提取data属性）
                            let columnNames = _dataList.v.tableArrangeList.map(function (col) {
                                return col.data;
                            });

                            // 服务器返回的数据通常位于json.data中（根据实际结构调整）
                            let rows = json.data || [];

                            // 预处理：为每行修补缺失字段
                            rows.forEach(function (row) {
                                columnNames.forEach(function (colName) {
                                    if (!row.hasOwnProperty(colName)) {
                                        row[colName] = '/'; // 缺失字段赋默认值0
                                    }
                                });
                            });

                            return rows;
                        }
                    },
                    "language": $tutu.v.dataTableL,
                    "columns": _dataList.v.tableArrangeList,
                    /*展示数据格式化*/
                    "createdRow": function (row, data, index) {
                        _dataList.v.list.push(data);
                    },
                    /*回调函数*/
                    rowCallback: function (row, data) {

                    },
                    /*带参数*/
                    "fnServerParams": function (aoData) {
                        _dataList.v.list = [];
                        aoData.sysTime = (Math.random() + Date.now());
                        aoData.deviceCode = $('#deviceList').val();
                        aoData.type = $('#typeList').val();
                        aoData.dataName = $('#searchKeyWord').val();
                        aoData.searchDate = $('#searchDate').val();
                    },
                    "fnDrawCallback": function (data) {
                        $tutu.uiForm(data);
                    }
                });
            },
            // 销毁现有的 DataTable 实例
            destroyDataTable: function () {
                if (_dataList.v.dTable !== null) {
                    _dataList.v.dTable.DataTable().destroy();
                    _dataList.v.dTable = null;
                    $('#dataTables').empty();
                }
            }
        }
    };

    $(document).ready(function () {
        _dataList.fn.init();

        window.onload = function () {
            checkSelectMenu("dataLi");

            loadMenuColor('dataLi');
        };
    });
</script>
</body>
</html>